<script setup lang="ts">
import { addPropertyFeeAPI, deletePropertyFeeAPI, getAllBuildingListAPI, getAllEnterpriseListAPI, getPropertyFeeDetailAPI, getPropertyFeeListAPI } from '@/apis/propertyfee'
import type { AllBuildingItemRes, AllEnterpriseItemRes, PropertyFeeAddParams, PropertyFeeDetailRes, PropertyFeeItemRes, PropertyFeeListParams } from '@/types/propertyfee'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { ref, watch } from 'vue'

const searchForm = ref<PropertyFeeListParams>({
  enterpriseName: '',
  start: '',
  end: '',
  page: 1,
  pageSize: 10
})

// 创建日期数组
const dateArr = ref<string[]>([])

// 监听日期数组
watch(dateArr, (newVal) => {
  if (newVal) {
    searchForm.value.start = newVal[0]
    searchForm.value.end = newVal[1]
  } else {
    searchForm.value.start = ''
    searchForm.value.end = ''
  }
})

const propertyList = ref<PropertyFeeItemRes[]>()
const total = ref(0)
// 获取物业费列表
const getPropertyList = async () => {
  const res = await getPropertyFeeListAPI(searchForm.value)
  propertyList.value = res.data.rows
  total.value = res.data.total
}
getPropertyList()

const handleSearch = () => {
  // 实现搜索逻辑
  getPropertyList()
}

// 添加账单
const addDialogVisible = ref(false)
const addForm = ref<PropertyFeeAddParams>({
  enterpriseId: undefined,
  buildingId: undefined,
  startTime: '',
  endTime: '',
  paymentAmount: undefined,
  paymentMethod: 1
})

// 查询所有楼宇
const buildingList = ref<AllBuildingItemRes[]>([])
const getBuildingList = async () => {
  const res = await getAllBuildingListAPI()
  buildingList.value = res.data
}

// 查询所有企业
const enterpriseList = ref<AllEnterpriseItemRes[]>([])
const getEnterpriseList = async () => {
  const res = await getAllEnterpriseListAPI()
  enterpriseList.value = res.data
}

// 添加日期数组
const addDateArr = ref<string[]>([])
watch(addDateArr, (newVal) => {
  if (newVal) {
    addForm.value.startTime = newVal[0]
    addForm.value.endTime = newVal[1]
  } else {
    addForm.value.startTime = ''
    addForm.value.endTime = ''
  }
})

// 缴费日期只能当天开始
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
}

// 表单规则
const addFormRules = ref({
  enterpriseId: [{ required: true, message: '请选择租户' }],
  buildingId: [{ required: true, message: '请选择租赁楼宇' }],
  startTime: [{ required: true, message: '请选择缴费日期' }],
  endTime: [{ required: true, message: '请选择缴费日期' }],
  paymentAmount: [{ required: true, message: '请输入支付金额' }],
  paymentMethod: [{ required: true, message: '请选择支付方式' }],
})

// 创建表单实例
const addFormRef = ref<FormInstance>()

// 添加处理函数
const handleAdd = () => {
  addDialogVisible.value = true
  getBuildingList()
  getEnterpriseList()
}
const handleAddClose = () => {
  addDialogVisible.value = false
}

const handleAddSubmit = async () => {
  // 先校验
  await addFormRef.value?.validate()

  await addPropertyFeeAPI(addForm.value)

  getPropertyList()
  ElMessage.success('添加成功')
  addDialogVisible.value = false
}

// 查看账单
const propertyDetail = ref<PropertyFeeDetailRes>()
const dialogVisible = ref(false)

const handleView = async (row: PropertyFeeItemRes) => {
  const res = await getPropertyFeeDetailAPI(row.id)
  propertyDetail.value = res.data
  dialogVisible.value = true
}

const handleClose = () => {
  dialogVisible.value = false
}

// 删除账单
const handleDelete = (row: PropertyFeeItemRes) => {

  try {
    ElMessageBox.confirm(
      '确定要删除吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      const res = await deletePropertyFeeAPI(row.id)
      console.log(res);

      ElMessage.success('删除成功')
      getPropertyList()

    }).catch()
  } catch (error) {
    console.log(error);

  }
}
</script>

<template>
  <div class="property-page">
    <div class="search-area">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="企业名称:">
          <el-input v-model="searchForm.enterpriseName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="缴费时间:">
          <el-date-picker v-model="dateArr" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
        {{ searchForm }}
      </el-form>
    </div>

    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">添加账单</el-button>
    </div>

    <el-table :data="propertyList" border style="width: 100%">
      <el-table-column type="index" label="序号" width="70" />
      <el-table-column prop="billNumber" label="账单编号" />
      <el-table-column prop="enterpriseName" label="企业名称" />
      <el-table-column prop="buildingName" label="租赁楼宇" />
      <el-table-column prop="propertyFeePrice" label="物业费(元/m²)" />
      <el-table-column prop="paymentAmount" label="账单金额(元)" />
      <el-table-column prop="createTime" label="缴费时间" />
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.pageSize"
      :page-sizes="[10, 15, 20]" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @change="getPropertyList" />


    <!-- 查看账单详情对话框 -->
    <el-dialog v-model="dialogVisible" title="查看账单" width="500px" :before-close="handleClose">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="租户名称">
          {{ propertyDetail?.enterpriseName }}
        </el-descriptions-item>
        <el-descriptions-item label="租赁楼宇">
          {{ propertyDetail?.buildingName }}
        </el-descriptions-item>
        <el-descriptions-item label="缴费周期">
          {{ propertyDetail?.startTime }} - {{ propertyDetail?.endTime }}
        </el-descriptions-item>
        <el-descriptions-item label="物业费(元/m²)">
          {{ propertyDetail?.propertyFeePrice }}
        </el-descriptions-item>
        <el-descriptions-item label="账单金额(元)">
          {{ propertyDetail?.paymentAmount }}
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">
          {{ propertyDetail?.paymentMethodValue }}
        </el-descriptions-item>
        <el-descriptions-item label="缴费时间">
          {{ propertyDetail?.createTime }}
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleClose">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加账单对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加账单" width="500px" :before-close="handleAddClose">
      <el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="选择租户" prop="enterpriseId">
          <el-select v-model="addForm.enterpriseId" placeholder="请选择租户">
            <el-option v-for="item in enterpriseList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select v-model="addForm.buildingId" placeholder="请选择租赁楼宇">
            <el-option v-for="item in buildingList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="缴费周期" prop="startTime">
          <el-date-picker v-model="addDateArr" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" :disabled-date="disabledDate" />
        </el-form-item>
        <el-form-item label="支付金额" prop="paymentAmount">
          <el-input v-model="addForm.paymentAmount" placeholder="请输入支付金额" type="number" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="addForm.paymentMethod" placeholder="请选择支付方式">
            <el-option label="微信" :value="1" />
            <el-option label="支付宝" :value="2" />
            <el-option label="现金" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      {{ addForm }}
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAddClose">取 消</el-button>
          <el-button type="primary" @click="handleAddSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.property-page {
  padding: 20px;

  .search-area {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
  }

  .operation-area {
    margin-bottom: 20px;
  }

  .dialog-footer {
    padding-top: 20px;
    text-align: right;
  }
}
</style>
